﻿package vsg.remote {
	
	import flash.external.ExternalInterface;
	import flash.net.URLLoader;
	import flash.events.*;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.net.URLRequestHeader;
	
	/**
	 * construct the Http Request Defined 
	 */
	public class FlashHttpRequest {

		private var debugCallJsFunction:String = "Vsg.FlashHttpRequest.flash_debug";
		
		private var callJsFunction:String = "Vsg.FlashHttpRequest.flash_reponseHandle";		
		
		public function FlashHttpRequest() {

		}
		
		/**
		 * invoke the complete handler for load complete  
		 */
		private function completeHandler(evt:Event) {
			ExternalInterface.call(callJsFunction, evt.target);
		}
		
		private function openHander(evt:Event) {
			//ExternalInterface.call("Vsg.FlashRemoteProxy.flash_debug","open daa");
		}
		
		private function ioErrorHandler(evt:IOErrorEvent) {
			var $result = {
				text:evt.text,
				target:evt.target
			}
			ExternalInterface.call("Vsg.FlashRemoteProxy.flash_failureHandle", $result);
		}
		
		private function httpStatusHandler(evt:HTTPStatusEvent) {
			var $result = {
				status:evt.status,
				target:evt.target
			}
			ExternalInterface.call("Vsg.FlashRemoteProxy.flash_httpStatus", $result);
		}
		
		private function sendRequest(opt:Object) {
			
			var $sendRequest:URLRequest = new URLRequest(); 
			var $variables:URLVariables = new URLVariables();
			var $loader:URLLoader = new URLLoader();

			
			try {
				var $url = opt.url;

				if (opt.params != null) {
					for (var i:String in opt.params) {
						$variables[i] = opt.params[i];
					}
				}
	

				$sendRequest.url = $url;
				$sendRequest.method = URLRequestMethod.POST; 
				$sendRequest.data = $variables.toString();
				
				
				// --- defined listener ---
				$loader.addEventListener(Event.OPEN, openHander);
				$loader.addEventListener(Event.COMPLETE, completeHandler);
				$loader.addEventListener(HTTPStatusEvent.HTTP_STATUS , httpStatusHandler);
				$loader.addEventListener(IOErrorEvent.IO_ERROR , ioErrorHandler);

				$loader.load($sendRequest);	
				
			} catch (err: Error) {
				ExternalInterface.call("Vsg.FlashRemoteProxy.flash_debug", err.toString());
			} finally {
				$sendRequest = null;
				$variables = null;
				$loader = null;

			}
		}
		
		
		/**
		 * send the request handle
		 */
		public function request(opt:Object):Number {
			// --- defined the url ---
			sendRequest( opt );

			var $runId:Number = 0
			
			return $runId;
		}
		
		
	}
	
}